﻿using System;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Newtonsoft.Json;
using BaseDll;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
namespace MotionIoLib
{
    public class TcpParameter
    {
        public string DefaultFilePath { get; set; } = "";
        public string Name { get; set; }

        public string IpAddress { get; set; } = "192.168.1.0";

        public int Port { get; set; } = 1000;

        public string EndString { get => Encoding.ASCII.GetString(new byte[] { 0x0D, 0x0A }); }
        public int Timeout { get; set; } = 100000;

        public TcpParameter(string str_IP, int n_Port, int n_TimeOut=3000)
        {
            this.IpAddress = str_IP;
            this.Port = n_Port;
            this.Timeout = n_TimeOut;
        }
    }

    public class RobotTcpClient
    {
        public TcpClient Client { get; private set; }

        public TcpParameter Parameter { get; set; }

        public void Init(string str_IP, int n_Port, int n_TimeOut = 100000)
        {
            Parameter = new TcpParameter(str_IP, n_Port, n_TimeOut);
            Client = new TcpClient();
        }

        public bool bIsConnected
        {
            get => Client.Connected;
        }

        public void Connect()
        {
            Client?.Connect(IPAddress.Parse(Parameter.IpAddress), Parameter.Port);
        }

        public void Close()
        {
            Client?.Close();
        }
        object lockSendObj = new object();
        byte[] ReciveData = new byte[1024];
        public bool bExit = false;
        public string SendCommand(string cmd, bool bIgnorRtn = false)
        {

            lock (lockSendObj)
            {
                try
                {
                    int offset = 0;
                    var client = Client.Client;
                    string EndString = "\r\n";
                    client.Send(Encoding.ASCII.GetBytes(cmd + EndString));
                    if (bIgnorRtn) return "0";
                    byte[] readBuffer = new byte[1024];
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    while (!bExit)
                    {
                        if (stopwatch.ElapsedMilliseconds >= Parameter.Timeout)
                        {
                            stopwatch.Stop();
                            throw new TimeoutException($"等待{Parameter.Name}的响应超时");
                        }
                        if (client.Available == 0)
                        {
                            System.Threading.Thread.Sleep(1);
                            continue;
                        }
                        System.Threading.Thread.Sleep(10);

                        if (client.Poll(1, SelectMode.SelectRead))
                        {
                            var bytesRead = client.Receive(ReciveData, offset,readBuffer.Length, SocketFlags.None);
                            offset += bytesRead;
                            if (offset >= 2 && ReciveData[offset - 2] == 0x0D && ReciveData[offset - 1] == 0x0A)
                            {
                                string str = Encoding.ASCII.GetString(ReciveData, 0, offset - 2);     
                                return str;
                            }
                        }
                    }
                    return "";
                }
                catch (Exception)
                {
                    return "";
                }
            }
         
        }

    }
}
